package com.rsy.demo.config;

import com.rsy.demo.internal.HelloWordService;
import com.rsy.demo.internal.HttpServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

@Configuration
public class NettyServerConfig {

    @Value("${netty.http.port:8081}")
    private int port;

    // 主线程组，负责接收客户端连接
    private EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    // 工作线程组，负责处理已建立的连接的 I/O 操作
    private EventLoopGroup workerGroup = new NioEventLoopGroup();

    /**
     * 启动 Netty 服务器
     *
     * @return 返回 ChannelFuture 用于同步等待服务器启动完成
     * @throws InterruptedException
     */

    @Bean
    public ChannelFuture startNettyServer(HelloWordService helloWordService) throws InterruptedException {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class) // 使用 NIO 模式
                .localAddress(new InetSocketAddress(port))
                .handler(new LoggingHandler(LogLevel.INFO)) // BossGroup 的日志处理器
                .childHandler(new ChannelInitializer<SocketChannel>() { // 为新建立的连接设置 Pipeline
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 添加编解码器和业务处理器
                        ch.pipeline().addLast(
                                new LoggingHandler(LogLevel.DEBUG), // 详细日志，便于调试
                                new HttpServerCodec(), // HTTP 编解码器：将字节流转换为 HttpRequest/HttpResponse
                                new HttpObjectAggregator(512 * 1024), // 聚合器：将多个 HTTP 消息部分合并为一个 FullHttpRequest/FullHttpResponse
                                new HttpServerHandler(helloWordService) // 我们自定义的业务逻辑处理器
                        );
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128) // 连接队列大小
                .childOption(ChannelOption.SO_KEEPALIVE, true); // 保持长连接

        ChannelFuture future = bootstrap.bind().sync(); // 绑定端口并启动，sync() 表示同步等待绑定成功
        System.out.println("Netty HTTP Server started on port: " + port);
        return future;
    }

    /**
     * 优雅关闭，释放线程组资源
     */
    @PreDestroy
    public void stop() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        System.out.println("Netty HTTP Server stopped.");
    }
}